package com.zzyl.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.ObjectUtil;
import com.zzyl.constant.SuperConstant;
import com.zzyl.dto.ResourceDto;
import com.zzyl.entity.Resource;
import com.zzyl.enums.BasicEnum;
import com.zzyl.exception.BaseException;
import com.zzyl.mapper.ResourceMapper;
import com.zzyl.service.ResourceService;
import com.zzyl.utils.NoProcessing;
import com.zzyl.vo.ResourceVo;
import com.zzyl.vo.TreeItemVo;
import com.zzyl.vo.TreeVo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Comparator;
import java.util.List;
import java.util.stream.Collectors;
import java.util.stream.Stream;

@Slf4j
@Service
public class ResourceServiceimpl implements ResourceService {
    @Autowired
    private ResourceMapper resourceMapper;

    @Override
    public List<ResourceVo> getlist(ResourceDto resourceDto) {
        List<Resource> resources = resourceMapper.getlist(resourceDto);
        return BeanUtil.copyToList(resources, ResourceVo.class);
    }

    @Override
    public TreeVo resourcetree(ResourceDto resourceDto) {

        ResourceDto dto = ResourceDto.builder()
                .parentResourceNo(NoProcessing.processString(SuperConstant.ROOT_PARENT_ID))
                .resourceType(SuperConstant.MENU)
                .dataState(SuperConstant.DATA_STATE_0)
                .build();
        List<Resource> resources = resourceMapper.getlist(dto);

        ArrayList<TreeItemVo> itemVos = new ArrayList<>();

        //组装树形结构
        //创建根节点
        Resource resource = new Resource();
        resource.setResourceNo(SuperConstant.ROOT_PARENT_ID);
        resource.setResourceName("智慧养老院");
        recursionTreeItem(itemVos, resource, resources);

        return TreeVo.builder().items(itemVos).build();
    }

    @Override
    public void createResource(ResourceDto resourceDto) {
        Resource resource = BeanUtil.toBean(resourceDto, Resource.class);
        //查询父资源
        Resource parentResource = resourceMapper.selectResourceNo(resourceDto.getParentResourceNo());
        //设置实体类的数据状态 为 父资源数据状态
        resource.setDataState(parentResource.getDataState());
        //判断当前新增的资源是否是 菜单
        boolean isMenu = true;
        if (SuperConstant.BUTTON.equals(resource.getResourceType())) {
            isMenu = false;
        }
        //生成资源编码
        String resourceNo = createResourceNo(resource.getParentResourceNo(), isMenu);
        resource.setResourceNo(resourceNo);
        resourceMapper.insert(resource);

    }

    @Override
    public void enable(ResourceDto resourceDto) {
        Resource resource = BeanUtil.toBean(resourceDto, Resource.class);
        //查询父资源
        Resource parentResource = resourceMapper.selectResourceNo(resourceDto.getParentResourceNo());
        log.info("resource.getDataState()================================" + resource.getDataState());
        if ("1".equals(resource.getDataState())) {
            resourceMapper.enable(resource);
            enableChlid(resourceDto, resource.getDataState());
        } else {
            String parentdataState = parentResource.getDataState();
            log.info("parentresourceNo=================================" + parentdataState);
            if ("1".equals(parentdataState)) {
                throw new BaseException(BasicEnum.PARENT_DEPT_DISABLE);
            } else {
                resourceMapper.enable(resource);
            }
        }

    }

    @Override
    public void delete(String resourceNo) {
        String s = NoProcessing.processString(resourceNo);
        resourceMapper.deleteByResourceNo(resourceNo);
        ResourceDto dto = ResourceDto.builder().parentResourceNo(s).build();
        List<Resource> list = resourceMapper.getlist(dto);
        for (Resource resource : list) {
            resourceMapper.deleteByResourceNo(resource.getResourceNo());
        }


    }

    @Override
    public void update(ResourceDto resourceDto) {
//        Long id = resourceDto.getId();
//        Resource resourceOld = resourceMapper.selectByPrimaryKey(id);
//        String resourceNo = resourceOld.getResourceNo();
//        ResourceDto dto = ResourceDto.builder().parentResourceNo(resourceNo).build();
//        List<Resource> list = resourceMapper.getlist(dto);
//        List<ResourceDto> resourceDtos = BeanUtil.copyToList(list, ResourceDto.class);
//        for (ResourceDto resourceDto1 : resourceDtos) {
//            String parentResourceNo = resourceDto1.getParentResourceNo();
//            log.info("parentResourceNo======================" + parentResourceNo);
//            Resource groundResourceNo = resourceMapper.selectResourceNo(parentResourceNo);
//            String parentResourceNo1 = groundResourceNo.getParentResourceNo();
//            resourceDto1.setParentResourceNo(parentResourceNo1);
//            createResource(resourceDto1);
//        }
//
//
//        createResource(resourceDto);
//        delete(resourceNo);

        //转换
        Resource resource = BeanUtil.toBean(resourceDto, Resource.class);
        int flag = resourceMapper.updateByPrimaryKeySelective(resource);
        if (flag == 0) {
            throw new RuntimeException("修改资源信息出错");
        }


    }

    private void enableChlid(ResourceDto root, String dataState) {
        String resourceNo = root.getResourceNo();
        String s = NoProcessing.processString(resourceNo);
        ResourceDto dto = ResourceDto.builder().parentResourceNo(s).build();
        List<Resource> list = resourceMapper.getlist(dto);
        for (Resource resource : list) {
            resource.setDataState(SuperConstant.DATA_STATE_1);
            log.info("resource.getResourceNo()============================================" + resource.getResourceNo());
            resourceMapper.enable(resource);
        }

    }

    private String createResourceNo(String ParentResourceNo, boolean isMenu) {
        //菜单 最大是三层
        //根节点 100 001 000 000 000
        //一级菜单 100 001 001 000 000
        //二级菜单 100 001 001 001 000
        //三级菜单 100 001 001 001 001
        if (isMenu && NoProcessing.processString(ParentResourceNo).length() / 3 >= 5) {
            throw new BaseException(BasicEnum.RESOURCE_DEPTH_UPPER_LIMIT);
        }
        //根据父资源编码 生成子资源编码
        ResourceDto dto = ResourceDto.builder().parentResourceNo(ParentResourceNo).build();
        List<Resource> list = resourceMapper.getlist(dto);
        if (ObjectUtil.isEmpty(list)) {
            return NoProcessing.createNo(ParentResourceNo, false);
        } else {
            String no = list.stream().map(s -> s.getResourceNo()).max((o1, o2) -> o1.compareTo(o2)).get();

            return NoProcessing.createNo(no, true);
        }

    }

    private void recursionTreeItem(ArrayList<TreeItemVo> itemVos, Resource root, List<Resource> resources) {
        //根据当前节点
        TreeItemVo treeItemVo = TreeItemVo.builder()
                .id(root.getResourceNo())
                .label(root.getResourceName()).build();

        List<Resource> list = resources.stream()
                .filter(n -> n.getParentResourceNo().equals(root.getResourceNo()))
                .collect(Collectors.toList());
        if (!ObjectUtil.isEmpty(list)) {
            ArrayList<TreeItemVo> childRenList = new ArrayList<>();

            list.forEach(resource -> recursionTreeItem(childRenList, resource, resources));

            treeItemVo.setChildren(childRenList);
        }
        itemVos.add(treeItemVo);
    }
}
